const mongoose = require('mongoose');
const async = require('async');
const Schema = mongoose.Schema;
const ObjectId = Schema.ObjectId;

const User = new Schema({
    name: String,
    email: String,
    password: String,
    profile_image: { type: String, default: '/dist/dashboard/images/default_profile_image.png' },
    hash_id: { type: String },
    industry: String,
    locale: { type: String, default: 'zh-CN' },
    type: { type: String, default: 'register' },
    ref: { type: String, default: 'direct' },
    created_date: { type: Date, default: Date.now },
    lossPercent: { type: Number, default: 0 }
});

User.statics.findUserByEmail = function (email, cb) {
    return this.find({ email: email }, cb);
};

User.statics.findUserByThirdPartyInfo = function (thirdPartyId, ref, cb) {
    return this.find({ third_party_id: thirdPartyId, ref: ref }, cb);
};

User.statics.findUserById = function (id, cb) {
    this.findById(id, cb)
};
User.statics.findUserByIdentifier = function (identifier, cb) {
    return this.find({ hash_id: identifier }, cb);
};
User.statics.getUsers = function (cb) {
    return this.find(cb);
};
User.statics.removeUserByUserId = function (user_id, cb) {
    return this.remove({ _id: user_id }, cb);
};

User.statics.findUsersByThirdPartyId = function (thirdPartyId, ref, cb) {
    return this.find({ third_party_id: thirdPartyId, ref: ref }, cb);
};

exports.User = User;

var SystemSetting = new Schema({
    user_id: String,
    setting_name: String,
    setting_value: { type: Schema.Types.Mixed, default: null },
    last_updated_date: { type: Date, default: Date.now },
    created_date: { type: Date, default: Date.now }
});

SystemSetting.statics.findSettingByName = function (userId, settingName, cb) {
    this.find({ user_id: userId, setting_name: settingName }, cb);
}

SystemSetting.statics.findSettingsByUserId = function (userId, cb) {
    this.find({ user_id: userId }, cb);
};


exports.SystemSetting = SystemSetting;

var LeadFlow = new Schema({
    user_id: String,
    name: String,
    settings: { type: Schema.Types.Mixed, default: {} },
    created_date: { type: Date, default: Date.now },
    last_updated_date: { type: Date, default: Date.now }
});

LeadFlow.statics.findLeadFlowsByUserId = function (userId, params, cb) {
    var me = this;
    var pageIndex = Number(params.pageIndex || 1);
    var pageSize = Number(params.pageSize || 5);
    var skipRecords = (pageIndex - 1) * pageSize;

    var conditions = {
        user_id: userId
    };

    var result = {
        pageIndex: pageIndex,
        pageSize: pageSize,
        pageCount: 0,
        totalCount: 0,
        leadflows: []
    };
    async.waterfall([
        (callback) => {
            me.find(conditions, (error, records) => {
                if (error) {
                    cb(error, result);
                } else {
                    callback(null, records);
                }
            });
        },
        (records, callback) => {
            result.pageCount = Math.ceil(records.length / pageSize);
            result.totalCount = records.length;
            me.find(conditions).sort({ created_date: -1 }).skip(skipRecords).limit(pageSize).exec((error, records) => {
                if (error) {
                    cb(error, result);
                } else {
                    result.leadflows = records;
                    cb(null, result);
                }
            });
        }
    ]);

}

LeadFlow.statics.getLeadFlowsByUserId = function (userId, cb) {
    var me = this;
    var conditions = {
        user_id: userId
    };
    var result = {
        leadflows: []
    };
    async.waterfall([
        (callback) => {
            me.find(conditions, (error, records) => {
                if (error) {
                    cb(error, result);
                } else {
                    callback(null, records);
                }
            });
        },
        (records, callback) => {
            me.find(conditions).exec((error, records) => {
                if (error) {
                    cb(error, result);
                } else {
                    result.leadflows = records;
                    cb(null, result);
                }
            });
        }
    ]);

}

LeadFlow.statics.findLeadFlowById = function (id, cb) {
    this.findById(id, cb);
};

LeadFlow.statics.removeById = function (id, cb) {
    this.findById(id).remove(cb);
}

exports.LeadFlow = LeadFlow;


/*   调查问卷 Schema
    Schema CollectedClue 
    frenquency  每个月下发多少次微信报
    whichDay  周几下发微信报
    time_interval 什么时间段下发微信报
    increased_fans 下发后会增加多少个粉丝
*/

var FHTLiteResearch = new Schema({
    user_agent: String,
    remote_ip: String,
    session_id: String,
    http_referer: String,
    send_frequency: Number,
    send_date: String,
    send_time_interval: String,
    increased_Fans: Number,
    total_Fans: Number,
    loss_rate: { type: Number, default: 0 },
});


FHTLiteResearch.statics.findAllLostRateByDescOrder = function (cb) {
    var me = this;
    me.find({}, { loss_rate: 1 }, { sort: { loss_rate: 1 } }, (error, records) => {
        cb(error, records);
    });
}

FHTLiteResearch.statics.findTotalFactor = function (conditions, cb) {
    var me = this;
    me.find(conditions, (error, records) => {
        cb(error, records);
    });
}


exports.FHTLiteResearch = FHTLiteResearch;

var CollectedLead = new Schema({
    leadflow_id: String,
    email: String,
    name: String,
    phone_number: String,
    session_id: String,
    remote_ip: String,
    http_referer: String,
    user_agent: String,
    created_date: { type: Date, default: Date.now },
    last_updated_date: { type: Date, default: Date.now },
    // timestamp: { type: Number, default: new Date().getTime() },
    trash: { type: Boolean, default: false }  //回收站字段用于区别是否为软性删除，默认为false，表示没有执行过删除操作，值为true，表示软性删除，可恢复
});

CollectedLead.statics.findLeadsByLeadflowId = function (leadflowId, params, cb) {
    var me = this;
    var pageIndex = Number(params.pageIndex || 1);
    var pageSize = Number(params.pageSize || 5);
    var skipRecords = (pageIndex - 1) * pageSize;
    var conditions = {
        leadflow_id: leadflowId
    };

    var result = {
        pageIndex: pageIndex,
        pageSize: pageSize,
        pageCount: 0,
        leads: []
    };

    async.waterfall([
        (callback) => {
            me.find(conditions, (error, records) => {
                if (error) {
                    cb(error, result);
                } else {
                    callback(null, records);
                }
            });
        },
        (records, callback) => {
            result.pageCount = Math.ceil(records.length / result.pageSize);
            result.totalCount = records.length;
            me.find(conditions).sort({ created_date: -1 }).skip(skipRecords).limit(pageSize).exec((error, records) => {
                if (error) {
                    cb(error, result);
                } else {
                    result.leads = records;
                    cb(null, result);
                }
            });
        }
    ]);
};
CollectedLead.statics.findLeadsByConditions = function (conditions, params, cb) {
    var me = this;
    var pageIndex = Number(params.pageIndex || 1);
    var pageSize = Number(params.pageSize || 5);
    var skipRecords = (pageIndex - 1) * pageSize;
    var result = {
        pageIndex: pageIndex,
        pageSize: pageSize,
        pageCount: 0,
        leads: []
    };
    async.waterfall([
        (callback) => {
            me.find(conditions, (error, records) => {
                if (error) {
                    cb(error, result);
                } else {
                    callback(null, records);
                }
            });
        },
        (records, callback) => {
            result.pageCount = Math.ceil(records.length / result.pageSize);
            result.totalCount = records.length;
            me.find(conditions).sort({ created_date: -1 }).skip(skipRecords).limit(pageSize).exec((error, records) => {
                if (error) {
                    cb(error, result);
                } else {
                    result.leads = records;
                    cb(null, result);
                }
            });
        }
    ]);
};

CollectedLead.statics.getCollectedDataByConditions = function (conditions, cb) {
    let me = this;
    let result = {
        leads: []
    };
    async.waterfall([
        (callback) => {
            me.find(conditions, (error, records) => {
                if (error) {
                    cb(error, result);
                } else {
                    callback(null, records);
                }
            });
        },
        (records, callback) => {
            me.find(conditions).sort({ created_date: -1 }).exec((error, records) => {
                if (error) {
                    cb(error, result);
                } else {
                    result.leads = records;
                    cb(null, result);
                }
            });
        }
    ]);
};

CollectedLead.statics.getDataByLeadflowId = function (leadflowId, cb) {
    var me = this;
    var conditions = {
        start_date: new Date().getTime() - 2592000000, // 1499918386801
        end_date: new Date().getTime() + 86400000 // 1499831986801
    };
    async.waterfall([
        (callback) => {
            me.find({leadflow_id: leadflowId}, {'$and': [{ created_date: { '$gte': conditions.start_date } }, { created_date: { '$lte': conditions.end_date } }] }, (error, records) => {
                if (error) {
                    cb(error, result);
                } else {
                    callback(null, records);
                }
            });
        },
        (records, callback) => {
            cb(null, records);
        }
    ]);
}

CollectedLead.statics.removeLeadsByLeadflowId = function (leadflowId, cb) {
    this.find({ leadflow_id: leadflowId }).remove(cb);
};

CollectedLead.statics.removeContactById = function (contactId, cb) {
    this.find({ id: contactId }).remove(cb);
};

CollectedLead.statics.findCollectedLeadById = function (id, cb) {
    this.findById(id, cb);
};


exports.CollectedLead = CollectedLead;


